package io.a.opencv;

import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;

public class Example {
    public static void main(String[] args) throws Exception {
        // RTSP 流地址
        String rtspUrl = "rtsp://10.10.40.209:8554/1";

        // 创建 FFmpegFrameGrabber 对象用于抓取 RTSP 流
        FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(rtspUrl);

        // 设置一些参数，比如视频格式、帧率等
        // grabber.setFormat("rtsp");
        // grabber.setFrameRate(30);

        // 启动抓取器
        grabber.start();

        // 设置抽帧间隔，例如每5帧抽一帧
        int frameInterval = 5;
        int frameNumber = 0;

        // 抽取帧
        Frame frame;
        while ((frame = grabber.grab()) != null) {
            if (frameNumber % frameInterval == 0) {
                // 转换为 BufferedImage
                Java2DFrameConverter converter = new Java2DFrameConverter();
                BufferedImage bufferedImage = converter.getBufferedImage(frame);

                // 保存图片
                File outputfile = new File("frame_" + frameNumber + ".png");
                ImageIO.write(bufferedImage, "png", outputfile);
            }
            frameNumber++;
        }

        // 停止抓取器并释放资源
        grabber.stop();
        grabber.release();
    }
}

